/**
 * Created by hanj on 2022/3/19 13:52
 */
package com.example.demo;

import com.example.demo.entity.Student;
import com.example.demo.util.ExcelUtil;
import com.example.demo.util.PackagingExcel;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;


/**
 * 线程1
 */
public class Thread1 implements Runnable {

    //通过上下文实现bean注入

    //线程计数器
    private CountDownLatch latch;

    private HttpServletResponse response;

    //压缩包地址
    private String dirPath;


    public Thread1() {
    }

    public Thread1(CountDownLatch latch, String dirPath,HttpServletResponse response) {
        this.latch = latch;
        this.dirPath = dirPath;
        this.response = response;
    }

    @Override
    public void run() {
        try {
            Map<String, List> result = new HashMap<>();
            System.out.println(Thread.currentThread().getName() + "future1启动中。。。。。。");
            List<Student> data = getData();
            result.put("1", data);
            //传输流
            OutputStream out = response.getOutputStream();
            ExcelUtil.exportSheetsTemplateByFill("templates/studentTemplate.xls", dirPath,
                    "student.xls", out, Thread1.class, result, null);
            System.out.println(Thread.currentThread().getName() + "future1打印：" + result);
        } catch (Exception e) {
            System.err.println(e.getMessage());
        } finally {
            latch.countDown();
            System.out.println(Thread.currentThread().getName() + "latch数量：" + latch.getCount());
        }
    }

    //模拟导出数据
    private List<Student> getData() {
        List<Student> result = new ArrayList<>();
        Student student = new Student();
        student.setName("张三");
        student.setAge(11);
        student.setAddress("中国");
        result.add(student);

        Student student1 = new Student();
        student1.setName("李四");
        student1.setAge(12);
        student1.setAddress("中国");
        result.add(student);
        return result;
    }
}
